package org.lab.tracecash.bootstrap;

import java.util.Calendar;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import org.lab.tracecash.guice.TracecashCoreModule;
import org.lab.tracecash.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.persist.PersistService;

public class TracecashBootstrap implements Runnable {

	private static final Logger LOG = LoggerFactory.getLogger(TracecashBootstrap.class);
	private static final String ADMIN_NAME = "admin";
	private static final String ADMIN_MAIL = "admin@tracecash.com";

	@Inject
	private Provider<EntityManager> entityManagerProvider;

	public static void main(String[] args) {
		Injector injector = Guice.createInjector(new TracecashCoreModule());
		injector.getInstance(PersistService.class).start();
		TracecashBootstrap bootstrap = injector.getInstance(TracecashBootstrap.class);
		bootstrap.run();
	}

	@Override
	public void run() {
		LOG.info("Starting Bootstrap");
		EntityManager entityManager = entityManagerProvider.get();
		entityManager.getTransaction().begin();
		if (isDatabaseInitialized()) {
			LOG.info("Database already initialized");
		} else {
			createSystemUsers();
			// TODO initial data load here
			LOG.info("Boostrap finished");
			entityManager.getTransaction().commit();
			LOG.info("Bootstrap completed");
		}
	}

	public Boolean isDatabaseInitialized() {
		TypedQuery<Long> query = entityManagerProvider.get().createQuery("select count(u) from User u", Long.class);
		return query.getSingleResult() > 0;
	}

	private void createSystemUsers() {
		entityManagerProvider.get().persist(new User(ADMIN_NAME, ADMIN_MAIL, "", Calendar.getInstance().getTime()));
	}
}
